#include "onlineremi.h"
#include "ui_onlineremi.h"

OnlineRemi::OnlineRemi(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::OnlineRemi)
{
    ui->setupUi(this);
    ui->remi_pakete_tableWidget->setColumnWidth(0, 60);
    ui->remi_pakete_tableWidget->setColumnWidth(1, 90);

    ui->lokal_paket_tableWidget->setColumnWidth(0, 150); // Titel
    ui->lokal_paket_tableWidget->setColumnWidth(1, 40);  // Ausgabe
    ui->lokal_paket_tableWidget->setColumnWidth(2, 40);  // Menge
    ui->lokal_paket_tableWidget->setColumnWidth(3, 90);  // GTIN
    ui->lokal_paket_tableWidget->setColumnWidth(4, 40);  // Addon


    db = QSqlDatabase::database();

    loadPakete();

    load_progress_label = new QLabel();
    load_progress_bar = new QProgressBar();
}

OnlineRemi::~OnlineRemi()
{
    delete ui;
}

void OnlineRemi::loadPakete()
{
    if ( db.isOpen() || db.open() )
    {
        ui->remi_pakete_tableWidget->clearContents();
        ui->remi_pakete_tableWidget->setRowCount(0);
        QSqlQuery q("SELECT paketnr, lfdnr, verarbeitung FROM online_pakete WHERE paketnr != '-1' ORDER BY verarbeitung DESC;", db);
        while ( q.next() )
        {
            ui->remi_pakete_tableWidget->insertRow( ui->remi_pakete_tableWidget->rowCount() );
            QTableWidgetItem *item = new QTableWidgetItem( q.value(1).toString() );
            item->setData(Qt::UserRole, q.value(0));
            ui->remi_pakete_tableWidget->setItem( ui->remi_pakete_tableWidget->rowCount()-1, 0, item );
            ui->remi_pakete_tableWidget->setItem( ui->remi_pakete_tableWidget->rowCount()-1, 1, new QTableWidgetItem( q.value(2).toDateTime().toString("dd.MM.yyyy hh:mm") ) );
        }

    }
}

void OnlineRemi::on_loadRemis_pushButton_clicked()
{
    disconnect(Rt::oc, SIGNAL(login_success()), this, SLOT(on_loadRemis_pushButton_clicked()));
    ui->loadRemis_pushButton->setEnabled(false);

    if ( !Rt::oc->isLogedIn() )
    {
        connect(Rt::oc, SIGNAL(login_success()), this, SLOT(on_loadRemis_pushButton_clicked()));
        Rt::oc->login();
        return;
    }

    if ( db.isOpen() || db.open() )
    {
        QSqlQuery lp("SELECT DISTINCT paket_id FROM remission ORDER BY paket_id DESC", db);
        while ( lp.next() )
        {
            QSqlQuery op("SELECT lfdnr FROM online_pakete WHERE lfdnr = '" + lp.value(0).toString() + "'");
            if ( !op.first() )
            {
                QByteArray data;
                data.append(QString("paketnr=%1").arg(lp.value(0).toString()));
                QNetworkRequest r(QUrl("http://www.leverdy.de/kdn_warenbewegung_paketsuche.php"));
                r.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
                loadReplys.insert("l"+lp.value(0).toString(), Rt::oc->getManager()->post(r, data));
                connect(loadReplys.value("l"+lp.value(0).toString()), SIGNAL(finished()), this, SLOT(loadReplyFinished()));
            }
        }
    }

    if ( !loadReplys.isEmpty() )
    {
        load_progress_label->setText(tr("Lade Online Remission ..."));
        load_progress_bar->setRange(0,0);
        load_progress_bar->setTextVisible(false);
        load_progress_bar->setFixedWidth(100);
        Rt::statusbar->addPermanentWidget(load_progress_label);
        Rt::statusbar->addPermanentWidget(load_progress_bar);
        load_progress_label->show();
        load_progress_bar->show();
    }
    else
        ui->loadRemis_pushButton->setEnabled(true);
}

void OnlineRemi::loadReplyFinished()
{
    QNetworkReply *reply = static_cast<QNetworkReply*>(sender());
    disconnect(reply, SIGNAL(finished()), this, SLOT(loadReplyFinished()));

    if ( loadReplys.key(reply).left(1) == "l" )
    {
        QString lfdnr = loadReplys.key(reply);
        lfdnr.remove(0,1);

        if ( reply->error() == QNetworkReply::NoError )
        {
            QWebPage page;
            page.currentFrame()->setHtml( QString::fromLatin1(reply->readAll()) );
            QWebElementCollection dom_td_collection = page.currentFrame()->findFirstElement("table[class=\"tabellenueberschrift\"]").nextSibling().findFirst("tr").findAll("td");
            QWebElement dom_a = dom_td_collection.at(1).findFirst("a");
            QRegExp rx("paketnr=([\\d]{1,8})&lfdnr=([\\d]{1,5})");
            QSqlQuery q(db);
            q.prepare("INSERT INTO online_pakete ( paketnr, lfdnr, verarbeitung ) VALUES ( :paketnr, :lfdnr, :verarbeitung);");
            if ( dom_a.attribute("href").contains(rx) && ( db.isOpen() || db.open() ) )
            {
                q.bindValue(":paketnr", rx.cap(1));
                q.bindValue(":lfdnr", rx.cap(2));
                q.bindValue(":verarbeitung", QDateTime::fromString(dom_td_collection.at(2).toPlainText(), "dd.MM.yyyy hh:mm"));

                /** Paketinhalt abrufen **/
                QByteArray data;
                data.append(QString("paketnr=%1&lfdnr=%2").arg(rx.cap(1), rx.cap(2)));
                QNetworkRequest r(QUrl("http://www.leverdy.de/kdn_warenbewegung_remipaket.php"));
                r.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
                loadReplys.insert("p"+rx.cap(1), Rt::oc->getManager()->post(r, data));
                connect(loadReplys.value("p"+rx.cap(1)), SIGNAL(finished()), this, SLOT(loadReplyFinished()));
            }
            else
            {
                q.bindValue(":paketnr", -1);
                q.bindValue(":lfdnr", lfdnr);
                q.bindValue(":verarbeitung", -1);
            }
            q.exec();
        }

        loadReplys.remove("l"+lfdnr);
    }

    if ( loadReplys.key(reply).left(1) == "p" )
    {
        QString paketnr = loadReplys.key(reply);
        paketnr.remove(0,1);
        qDebug() << "Remi geladen" << paketnr;

        if ( reply->error() == QNetworkReply::NoError )
        {
            QSqlQuery q(db);

            QWebPage page;
            page.currentFrame()->setHtml( QString::fromLatin1(reply->readAll()) );
            qDebug() << "Output" << page.currentFrame()->findFirstElement("table[class=\"tabellenueberschrift\"]").nextSibling().toPlainText();
            foreach ( QWebElement dom_tr, page.currentFrame()->findFirstElement("table[class=\"tabellenueberschrift\"]").nextSibling().findAll("tr") )
            {
                QWebElementCollection dom_td_collection = dom_tr.findAll("td");
                q.prepare("INSERT INTO online_remis ( objektnr, anr, menge, bezeichnung, paketnr ) VALUES ( :objektnr, :anr, :menge, :bezeichnung, :paketnr );");
                q.bindValue(":objektnr", dom_td_collection[2].toPlainText());
                q.bindValue(":anr", dom_td_collection[3].toPlainText());
                q.bindValue(":menge", dom_td_collection[1].toPlainText());
                q.bindValue(":bezeichnung", dom_td_collection[5].toPlainText());
                q.bindValue(":paketnr", paketnr);
                q.exec();
                qDebug() << q.lastError();
            }
        }

        loadReplys.remove("p"+paketnr);
    }

    if ( loadReplys.isEmpty() )
    {
        loadPakete();
        Rt::statusbar->removeWidget(load_progress_label);
        Rt::statusbar->removeWidget(load_progress_bar);
        ui->loadRemis_pushButton->setEnabled(true);
    }
}

void OnlineRemi::on_remi_pakete_tableWidget_itemSelectionChanged()
{
    if ( db.isOpen() || db.open() )
    {
        ui->online_paket_tableWidget->clearContents();
        ui->online_paket_tableWidget->setRowCount(0);

        ui->lokal_paket_tableWidget->clearContents();
        ui->lokal_paket_tableWidget->setRowCount(0);

        QSqlQuery q(db);

        /** Online Remis aus Datenbank laden **/
        q.prepare("SELECT bezeichnung, anr, menge FROM online_remis WHERE paketnr = :paketnr ORDER BY bezeichnung");
        q.bindValue("paketnr", ui->remi_pakete_tableWidget->selectedItems().first()->data(Qt::UserRole));
        q.exec();
        while ( q.next() )
        {
            int row = ui->remi_pakete_tableWidget->rowCount();
            ui->remi_pakete_tableWidget->insertRow( row );
            ui->remi_pakete_tableWidget->setItem( row, 0, new QTableWidgetItem(q.value(0).toString()) );
            ui->remi_pakete_tableWidget->item(row, 0)->setToolTip(q.value(0).toString());
            ui->remi_pakete_tableWidget->setItem( row, 1, new QTableWidgetItem(q.value(1).toString()) );
            ui->remi_pakete_tableWidget->setItem( row, 2, new QTableWidgetItem(q.value(2).toString()) );
        }

        /** Lokale Remis aus Datenbank laden **/
        q.prepare("SELECT titel, menge, gtin, addon FROM remission WHERE paket_id = :paket_id ORDER BY titel");
        q.bindValue("paket_id", ui->remi_pakete_tableWidget->selectedItems().first()->text());
        q.exec();
        while ( q.next() )
        {
            int row = ui->lokal_paket_tableWidget->rowCount();
            ui->lokal_paket_tableWidget->insertRow( row );
            ui->lokal_paket_tableWidget->setItem( row, 0, new QTableWidgetItem(q.value(0).toString()) );
            ui->lokal_paket_tableWidget->item(row, 0)->setToolTip(q.value(0).toString());
            ui->lokal_paket_tableWidget->setItem( row, 1, new QTableWidgetItem(da.getAusgabe(q.value(2).toString(), q.value(3).toString())) );
            ui->lokal_paket_tableWidget->setItem( row, 2, new QTableWidgetItem(q.value(1).toString()) );
            ui->lokal_paket_tableWidget->setItem( row, 3, new QTableWidgetItem(q.value(2).toString()) );
            ui->lokal_paket_tableWidget->setItem( row, 4, new QTableWidgetItem(q.value(3).toString()) );
        }
    }
}
